package vn.conghuy.talkwithme.responsor.responsor;

import java.util.ArrayList;

import vn.conghuy.talkwithme.data.sqlmodel.SqlData;
import vn.conghuy.talkwithme.data.sqlmodel.StaticInfoModel;
import vn.conghuy.talkwithme.data.sqlmodel.TemplatePair;
import vn.conghuy.talkwithme.utils.Utils;

public class TemplateResponsor extends Responsor {
	
	private static final String LEFT_SHARP_BRACKET = "<";
	private static final String RIGHT_SHARP_BRACKET = ">";
	
	public TemplateResponsor() {
	}
	
	@Override
	public String response(String request) {
		if(Utils.isExistStringInArray(SqlData.askNames, request)){
			String[] answerNames = TemplatePair.getAnswerByAskName(request);
			String answer = Utils.getRandomString(answerNames);
			
			answer = parseAnswer(answer);
			
			return answer;
		}
		return super.response(request);
	}
	
	//some answer has LEFT_SHARP_BRACKET and RIGHT_SHARP_BRACKET sign. it can be replace by an static info in database. this function will parse it
	private String parseAnswer(String answer){
		ArrayList<String> lSubString = new ArrayList<String>();
		int indexOpen = answer.indexOf(LEFT_SHARP_BRACKET);
		int indexClose = answer.indexOf(RIGHT_SHARP_BRACKET);
		String sFinal = "";
		while(indexOpen != -1 && indexClose != -1){
			// get substring before LEFT_SHARP_BRACKET
			if(indexOpen > 0){
				String sub1 = answer.substring(0, indexOpen - 1);
				lSubString.add(sub1);
				answer = answer.substring(indexOpen);
				indexClose = indexClose - sub1.length();
			}
			
			//get substring from LEFT_SHARP_BRACKET to RIGHT_SHARP_BRACKET
			if(indexClose > 0){
				String sub2 = answer.substring(0, indexClose);
				lSubString.add(sub2);
				answer = answer.substring(indexClose);
			}
			indexOpen = answer.indexOf(LEFT_SHARP_BRACKET);
			indexClose = answer.indexOf(RIGHT_SHARP_BRACKET);
		}
		if(answer.length() > 0)
			lSubString.add(answer);
		
		for(int i = 0; i < lSubString.size(); i++){
			String sub = lSubString.get(i);
			if(sub.startsWith(LEFT_SHARP_BRACKET)){
				String keyword = sub.substring(1, sub.length()-1);
				String name = StaticInfoModel.getName(keyword);
				sFinal += name;
			}
			else{
				sFinal += sub;
			}
			sFinal += " ";	
		}
			
		return sFinal;
	}

}
